package com.css.spring.formework.webmvc;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ViewResolver {

    private String viewName;
    private File templateFile;

    public ViewResolver(String viewName, File templateFile) {
        this.viewName = viewName;
        this.templateFile = templateFile;
    }

    public String viewResolver(ModelAndView modelAndView) throws IOException {
        StringBuilder sb = new StringBuilder();

//        RandomAccessFile ra = new RandomAccessFile(templateFile, "r");
        BufferedReader reader = new BufferedReader(new FileReader(templateFile));
        String line = null;
        while (null != (line = reader.readLine())) {
            Matcher matcher = matcher(line);
            while (matcher.find()) {
                int groupCount = matcher.groupCount();
                for (int i = 1; i <= groupCount; i++) {
                    String paramName = matcher.group(i);
                    Object paramValue = modelAndView.getModel().get(paramName);
                    if (paramValue == null) {
                        continue;
                    }
                    line = line.replaceAll("\\$\\{" + paramName + "\\}", paramValue.toString());
                }
            }
            sb.append(line);
        }
        return sb.toString();
    }

    private Matcher matcher(String str) {
        Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
        return pattern.matcher(str);
    }

    public String getViewName() {
        return viewName;
    }

    public void setViewName(String viewName) {
        this.viewName = viewName;
    }

    public File getTemplateFile() {
        return templateFile;
    }

    public void setTemplateFile(File templateFile) {
        this.templateFile = templateFile;
    }
}
